import React, {FC, useState, createContext, PropsWithChildren, useEffect} from 'react';
import {useNavigate} from "react-router";
import {getSession} from "@bastet/utils";


type AuthorityContext = {
  authority: any;
  setAuthority: (arg: string) => void;
  removeAuthority: () => void;
};

export const AuthorityContext = createContext<AuthorityContext>(
  {} as AuthorityContext
);

export const AuthorityProvider: FC<PropsWithChildren> = ({ children }: any) => {
  const [authority, setAuth] = useState<boolean>(false);
  const navigate = useNavigate();

  useEffect(() => {
    if (!authority) {
      const token = getSession('token');
      // console.log('auth: => ', token);
      if (token) {
        setAuth(true)
      } else {
        // visitor: 游客
        navigate('/visitor/login')
      }
    }
  }, [authority]);

  const setAuthority = (auth: string) => {
    setAuth(true);
    sessionStorage.setItem('auth', auth)
  };

  const removeAuthority = () => {
    setAuth(true);
    sessionStorage.removeItem('auth')
  };

  return (
    <AuthorityContext.Provider value={{ authority, setAuthority, removeAuthority }}>
      {children}
    </AuthorityContext.Provider>
  );
};
